package com.bjpowernode.listner;

import cn.hutool.bloomfilter.BitMapBloomFilter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bjpowernode.model.QueueConstant;
import com.bjpowernode.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class SpikeListener {

    @Resource
    private OrderService orderService;
    @Resource
    private BitMapBloomFilter bloomFilter;
    /**
     * 处理抢购的监听
     */
    @RabbitListener(queues = QueueConstant.SPIKE_QUEUE,concurrency = "3-5")
    public void spikeHandler(Message message, Channel channel) {
        // 取得消息唯一标示
        String messageId = message.getMessageProperties().getMessageId();
        // 拿到消息的id
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        JSONObject jsonObject = JSON.parseObject(new String(message.getBody()));
        Integer userId = jsonObject.getInteger("userId");
        String houseId = jsonObject.get("houseId").toString();
        // 判断是否重复的消息队列,如果是直接签收
//        if (bloomFilter.contains(messageId)) {
//            // 直接签收
//            try {
//                channel.basicAck(deliveryTag,false);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            return;
//        }
        // 操作数据库写订单表，修改房屋表
        try {
            orderService.doSpike(userId, houseId);
            log.info("抢购成功,用户id为{}，房间id为{}", userId, houseId);
            channel.basicAck(deliveryTag,false);
        } catch (IOException e) {
            log.error("抢购失败,用户为{}，房间id为{}", userId, houseId);
            e.printStackTrace();
        }

    }

}
